//
//  Message_RootViewController.m
//  Coding_My
//
//  Created by showXxie on 2017/8/22.
//  Copyright © 2017年 sooxie. All rights reserved.
//

#import "Message_RootViewController.h"
#import "ConversationCell.h"
#import "ToMessageCell.h"
#import "RDVTabBarController.h"
#import "RDVTabBarItem.h"
#import "ConversationViewController.h"
#import "SVPullToRefresh.h"
#import "PrivateMessages.h"

@interface Message_RootViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) ODRefreshControl *refreshControl;
@property (strong, nonatomic) PrivateMessages *myPriMsgs;

@end

@implementation Message_RootViewController



#pragma mark TabBar
- (void)tabBarItemClicked{
    [super tabBarItemClicked];
    if (_myTableView.contentOffset.y > 0) {
        [_myTableView setContentOffset:CGPointZero animated:YES];
    }else if (!self.refreshControl.isAnimating){
        [self.refreshControl beginRefreshing];
        [self.myTableView setContentOffset:CGPointMake(0, -44)];
        [self refresh];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.view.backgroundColor = [UIColor orangeColor];
    self.title = @"消息";
    _myPriMsgs = [[PrivateMessages alloc] init];
    
    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"tweetBtn_Nav"] style:UIBarButtonItemStylePlain target:self action:@selector(sendMsgBtnClicked:)] animated:NO];
    //    添加myTableView
    _myTableView = ({
        UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        tableView.backgroundColor = [UIColor clearColor];
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [tableView registerClass:[ConversationCell class] forCellReuseIdentifier:kCellIdentifier_Conversation];
        [tableView registerClass:[ToMessageCell class] forCellReuseIdentifier:kCellIdentifier_ToMessage];
        [self.view addSubview:tableView];
        [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
        {
            UIEdgeInsets insets = UIEdgeInsetsMake(0, 0, CGRectGetHeight(self.rdv_tabBarController.tabBar.frame), 0);
            tableView.contentInset = insets;
            tableView.scrollIndicatorInsets = insets;
        }
        tableView;
    });
    _refreshControl = [[ODRefreshControl alloc] initInScrollView:self.myTableView];
    [_refreshControl addTarget:self action:@selector(refresh) forControlEvents:UIControlEventValueChanged];
    
    __weak typeof(self) weakSelf = self;
    [_myTableView addInfiniteScrollingWithActionHandler:^{
        [weakSelf refreshMore];
    }];
    
    [self.refreshControl beginRefreshing];
    [self.myTableView setContentOffset:CGPointMake(0, -44)];
    [self refresh];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self refresh];
}


#pragma mark - 更新数据
- (void)refresh{
    
    __weak typeof(self) weakSelf = self;
    
//    [[NetAPIManager manager] request_UnReadNotificationsWithBlock:^(id data, NSError *error) {
//        
//        [weakSelf.myTableView reloadData];
//
//        
//    }];
    
    if (_myPriMsgs.isLoading) {
        return;
    }
    _myPriMsgs.willLoadMore = NO;
    [self sendRequest_PrivateMessages];

}

- (void)sendRequest_PrivateMessages{
    __weak typeof(self) weakSelf = self;
    
    [[NetAPIManager manager] request_PrivateMessages:_myPriMsgs andBlock:^(id data, NSError *error) {
        
        [weakSelf.refreshControl endRefreshing];
        [weakSelf.myTableView.infiniteScrollingView stopAnimating];
        
        NSDictionary *dicdata = data[@"data"];
        
        PrivateMessages *primsgs = [PrivateMessages mj_objectWithKeyValues:dicdata];
        
        [weakSelf.myPriMsgs configWithObj:primsgs];
        
        [weakSelf.myTableView reloadData];
        
        weakSelf.myTableView.showsInfiniteScrolling = weakSelf.myPriMsgs.canLoadMore;

        
    }];
    
    
    
    

}



- (void)refreshMore {
    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [self.refreshControl endRefreshing];
//        [self.myTableView.infiniteScrollingView stopAnimating];
//    });
    
}


- (void)sendMsgBtnClicked:(id)sender{
    
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger row = 3;
    if (_myPriMsgs.list) {
        row += [_myPriMsgs.list count];
    }
    return row;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row < 3) {
        ToMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_ToMessage forIndexPath:indexPath];
        switch (indexPath.row) {
            case 0:
                cell.type = ToMessageTypeAT;
                break;
            case 1:
                cell.type = ToMessageTypeComment;
                break;
            default:
                cell.type = ToMessageTypeSystemNotification;
                break;
        }
//        [tableView addLineforPlainCell:cell forRowAtIndexPath:indexPath withLeftSpace:75 hasSectionLine:NO];
        return cell;
    }else{
        
        ConversationCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_Conversation forIndexPath:indexPath];
      
        PrivateMessage *msg = [_myPriMsgs.list objectAtIndex:indexPath.row-3];
     
        cell.curPriMsg = msg;

        return cell;
        
    }


}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{


    return 61;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.row >= 3) {
        PrivateMessage *curMsg = [_myPriMsgs.list objectAtIndex:indexPath.row-3];

        ConversationViewController *vc = [[ConversationViewController alloc] init];
        
        User *curFriend = curMsg.friend;
        
        vc.myPriMsgs = [PrivateMessages priMsgsWithUser:curFriend];


        [self.navigationController pushViewController:vc animated:YES];
    }


}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
